/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uit.ieproject.utilites;

import java.awt.Color;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

/**
 *
 * @author Maivia
 */
public class TextpaneUtil {
    
    
    public static void setForegroundForTextpane(JTextPane textpane, Color color) {
        Style style = textpane.addStyle("style", null);
        StyleConstants.setForeground(style, color);
        StyledDocument doc = textpane.getStyledDocument();        
        doc.setCharacterAttributes(0, doc.getLength(), textpane.getStyle("style"), true);
    }
    
    public static void setTextPane(JTextPane textpane, String text, Color color) {
        StyledDocument doc = textpane.getStyledDocument();
        Style style = textpane.addStyle("I'm a Style", null);
        StyleConstants.setForeground(style, color);
        try {
            doc.insertString(doc.getLength(), text, style);
        } catch (BadLocationException e) {
        }
    }
    
    
    public static void setBackgroundColorText(JTextPane textpane, int start, int end, Color color) {
        Highlighter hilite = textpane.getHighlighter();
        DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(color);
        try {
            hilite.addHighlight(start, end, painter);
        } catch (BadLocationException e) {
        }
    }
    
    public static void removeAllAtrributes(JTextPane textpane) {
        StyledDocument doc = textpane.getStyledDocument();
        SimpleAttributeSet attr = new SimpleAttributeSet();
        StyleConstants.setForeground(attr, Color.black);
        StyleConstants.setBold(attr, false);
        doc.setCharacterAttributes(0, doc.getLength(), attr, false);
    }
    
    public static void setHighlighterForCheckInput(String regex, JTextPane textpane, Color color) {
        try {
            Document doc = textpane.getDocument();
            String content = doc.getText(0, doc.getLength());
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            while (matcher.find()) {
                System.out.println("5");
                int start = matcher.start();
                int end = matcher.end();
                TextpaneUtil.setBackgroundColorText(textpane, start, end, color);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
